package com.wedo.mall.payment;

import android.app.Activity;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.braintreepayments.api.dropin.DropInActivity;
import com.braintreepayments.api.dropin.DropInRequest;
import com.braintreepayments.api.dropin.DropInResult;
import com.e.library.activity.EActivity;
import com.e.library.entity.User;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.listener.EListener;
import com.e.library.utils.EGsonUtils;
import com.ipay.Ipay;
import com.ipay.IpayPayment;
import com.ipay.IpayResultDelegate;
import com.wedo.mall.BuildConfig;
import com.wedo.mall.R;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.dialog.InputPasswordDialog;
import com.wedo.mall.dialog.PayPasswordDialog;
import com.wedo.mall.widget.PaymentView;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;

/**
 * 支付
 * @author lxy
 * @time 2017/8/8  14:28
 */
public class Payment{

    private String amount;
    private String currency = "RM";
    private transient EActivity mActivity;
    private transient OnPayListener mListener;

    public static Payment with(EActivity activity){
        return new Payment(activity);
    }

    public Payment(EActivity activity) {
        this.mActivity = activity;
    }

    public Payment amount(String amount){
        this.amount = amount;
        return this;
    }

    public Payment currency(String currency){
        this.currency = currency;
        return this;
    }

    public Payment listener(OnPayListener listener){
        this.mListener = listener;
        return this;
    }

    public void onPaySelected(PaymentView pv_payment){
        if (pv_payment.iPay88()){
        } else if(pv_payment.paypal()) {
            paypal();
        }else if(pv_payment.balance()) {
            if(!pv_payment.balanceEnough(amount)) {
                mActivity.toast(R.string.payment_no_enough);
            }else if (pv_payment.hasPassword()){
                showPayPassword();
            }else {
                showSetPassword(pv_payment);
            }
        }else {
            mActivity.toast(R.string.payment_coming_soon);
        }
    }

    public void showSetPassword(final PaymentView pv_payment){
        PayPasswordDialog dialog = new PayPasswordDialog(mActivity);
        dialog.setListener(new EListener<String>() {
            @Override
            public void onInvoked(View view, String data, int position) {
                setPassword(pv_payment,data);
            }
        });

        dialog.show();
    }

    private void setPassword(final PaymentView pv_payment,final String password){
        mActivity.loading();
        Map<String,String> params = new HashMap<>();
        params.put("password",password);
        EClient.with().post(EApi.USER_EDITPAYPASSWORD, params, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mActivity.dismiss(R.string.user_passwordsuccessful);
                pv_payment.onSetPassword(password);
                showPayPassword();
            }

            @Override
            public void failure(String msg) {
                mActivity.dismiss(msg);
            }
        });
    }

    public void showPayPassword(){
        InputPasswordDialog dialog = new InputPasswordDialog(mActivity);
        dialog.setListener(new EListener<String>() {
            @Override
            public void onInvoked(View view, String data, int position) {
                verifyPassword(data);
            }
        });

        dialog.show();
    }

    public void verifyPassword(final String password){
        mActivity.loading();
        Map<String,String> params = new HashMap<>();
        params.put("password",password);
        EClient.with().post(EApi.USER_VERIFYPAYPASSWORD, params, new EObserver() {
            @Override
            public void successful(EResponse response) {
                balance();
            }

            @Override
            public void failure(String msg) {
                mActivity.dismiss(msg);
            }
        });
    }

    /**余额支付*/
    public void balance(){
        mActivity.loading();
        Map<String,String> params = new HashMap<>(1);
        params.put("money",amount);
        Observable<EResponse> observable = EClient.with().api().post(EApi.MONEY_BALANCE_PAY,params);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mActivity.dismiss();
                onPaySuccessful();
            }

            @Override
            public void failure(String msg) {
                mActivity.dismiss(msg);
            }
        });
    }

    /**获取PayPal支付token*/
    public void paypal(){
        mActivity.loading();

        Map<String,String> params = new HashMap<>();
        Observable<EResponse> observable = mActivity.api().post(EApi.PAYMENT_PAYPAL,params);
        mActivity.observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mActivity.dismiss();
                String token = response.string("clientToken");
                toPayPal(token);
            }

            @Override
            public void failure(String msg) {
                mActivity.dismiss(msg);
            }
        });

    }

    private void toPayPal(String token){
        DropInRequest dropInRequest = new DropInRequest()
                .clientToken(token).amount(amount).disableAndroidPay()
                .collectDeviceData(true);
        mActivity.startActivityForResult(dropInRequest.getIntent(mActivity), PaymentView.PAYMENT_PAYPAL);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == PaymentView.PAYMENT_PAYPAL) {
            if (resultCode == Activity.RESULT_OK) {
                DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
                onPaySuccessful();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                mActivity.toast(R.string.payment_cancel);
            } else {
                Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR);
                mActivity.toast(R.string.payment_exception);
            }
        }
    }

    public void iPay88(){

        User user = WLogin.user();
        IpayPayment payment = new IpayPayment();
        payment.setMerchantKey("eDp5HeF7HN");
        payment.setMerchantCode("M12565");
        payment.setPaymentId("6");
       //payment.setCurrency(currency);
        payment.setRefNo("");
        payment.setAmount(amount);
        payment.setProdDesc("");
        payment.setUserName(user.nickname);
        payment.setUserEmail(user.username);
        payment.setUserContact("");
        payment.setRemark("");
//        payment.setLang("");
//        payment.setCountry("");
//        payment.setBackendPostURL("");
        Intent checkoutIntent = Ipay.getInstance().checkout(payment, mActivity, new IPay88Delegate(this));
        mActivity.startActivityForResult(checkoutIntent, PaymentView.PAYMENT_IPAY88);
    }

    public void iPay88Order(String order_sn,double amount){
        this.amount = String.format("%.2f", amount);
        Map<String,String> params = new HashMap<>(2);
        params.put("order_sn",order_sn);
        iPay88(EApi.PAYMENT_IPAY88,params);
    }

    public void iPay88Scan(String agent_id,String total){
        Map<String,String> params = new HashMap<>(2);
        params.put("agent_id",agent_id);
        params.put("total",total);
        iPay88(EApi.PAYMENT_IPAY88_SCAN,params);
    }

    private void iPay88(String url,Map<String,String> params){
        mActivity.loading();
        Observable<EResponse> observable = mActivity.api().post(url,params);
        mActivity.observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mActivity.dismiss();
                IpayPayment payment = response.object("appApiParameters",IpayPayment.class);
                User user = response.user();
                toIPay88(payment,user);
            }

            @Override
            public void failure(String msg) {
                mActivity.dismiss(msg);
            }
        });
    }

    private void toIPay88(IpayPayment payment,User user){
        if (payment == null){
            return;
        }

        try {

            payment.setPaymentId("6");
            payment.setMerchantKey("eDp5HeF7HN");

            payment.setUserName(user.nickname);
            if(TextUtils.isEmpty(payment.getUserEmail())) {
                payment.setUserEmail(user.username);//用户邮箱
            }

            if(TextUtils.isEmpty(payment.getAmount())) {
                payment.setAmount(amount);//金额
            }

            /**------test-----**/
            if(BuildConfig.DEBUG) {
                payment.setAmount("1.00");
                payment.setUserEmail("570655893@qq.com");

                payment.setProdDesc("wedo- Pay for order number");
                payment.setRefNo("order");
            }
            Log.i("payment", EGsonUtils.toJson(payment));
            Intent intent = Ipay.getInstance().checkout(payment, mActivity, new IPay88Delegate(this));
            mActivity.startActivityForResult(intent, PaymentView.PAYMENT_IPAY88);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void onPaySuccessful(){
        if(mListener !=null) {
            mListener.successful();
        }
    }

    public interface OnPayListener{
        void successful();
    }
}
